package cn.sumpu.app.guoguojie.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import cn.sumpu.app.guoguojie.domain.MemberDetail;
import cn.sumpu.app.guoguojie.biz.MemberBiz;
import cn.sumpu.app.guoguojie.biz.MemberDetailBiz;
import cn.sumpu.app.guoguojie.domain.BonusApply;
import cn.sumpu.app.guoguojie.domain.Doing;
import cn.sumpu.app.guoguojie.domain.DoingPictorial;
import cn.sumpu.app.guoguojie.domain.Member;
import cn.sumpu.app.guoguojie.domain.Order;
import cn.sumpu.app.guoguojie.domain.OrderProduct;
import cn.sumpu.app.guoguojie.domain.PictorialTopic;
import cn.sumpu.app.guoguojie.biz.BonusBiz;
import cn.sumpu.app.guoguojie.biz.DoingBiz;
import cn.sumpu.app.guoguojie.biz.IdentifierBiz;
import cn.sumpu.app.guoguojie.biz.PictorialTopicBiz;
import cn.sumpu.app.guoguojie.biz.ProductBiz;
import cn.sumpu.app.guoguojie.constant.AlertMsgCode;
import cn.sumpu.app.guoguojie.constant.BonusType;
import cn.sumpu.app.guoguojie.dao.BonusDao;
import cn.sumpu.app.guoguojie.domain.Bonus;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.AlertMsg;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.Constant;
import cn.sumpu.app.guoguojie.util.PageModel;
import cn.sumpu.app.guoguojie.util.PageSize;

public class BonusBizImpl implements BonusBiz {

	@Resource
	private PictorialTopicBiz pictorialTopicBiz;
	private BonusDao bonusDao;
	@Resource
	private DoingBiz doingBiz;
	@Resource
	private MemberDetailBiz memberDetailBiz;
	@Resource
	private MemberBiz memberBiz;
	@Resource
	private ProductBiz productBiz;
	@Resource
	private IdentifierBiz identifierBiz;
	
	private DataSourceTransactionManager transactionManager;

	
	public void setTransactionManager(
			DataSourceTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}
	public void setBonusDao(BonusDao bonusDao) {
		this.bonusDao = bonusDao;
	}

	//添加红利
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout=10)
	public void addBonus(Bonus bonus) throws AppBusinessException {
		String identifier = identifierBiz.generateId("bonus");
		bonus.setIdentifier(identifier);
		bonus.setLeaveAmount(bonus.getAmount());
		bonusDao.addBonus(bonus);
		//添加主题
		PictorialTopic pt = new PictorialTopic();
		pt.setIdentifier(identifierBiz.generateId("pictorial_topic"));
		pt.setName(bonus.getName());
		pt.setDescription(bonus.getIntro());
		pt.setType(Constant.PIC_TOPIC_TYPE_BONUS);
		pt.setBonus(identifier);
		pictorialTopicBiz.addPictorialTopic(pt);
	}
	//在后台查询所有红利
	@Override
	public PageModel getBonusAll(Integer pageSize, Integer page) throws AppBusinessException {
		if(page==null || page<1)
			page = 1;
		if(pageSize==null || pageSize<1)
			pageSize = 10;
		Map<String,Object> map = new HashMap<String,Object>();
		int count = bonusDao.getBonusListCount(map);
		Integer startId = (page - 1) * pageSize;
		map.put("startId", startId);
		map.put("pageSize", pageSize);
		List<Bonus> bonusList = bonusDao.getBonusList(map);
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(bonusList);
		pm.setPageSize(pageSize);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + pageSize- 1) / pageSize);
		return pm;
	}
	//更新红利
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout=10)
	public void updateBonusById(Bonus bonus) throws AppBusinessException {
		bonusDao.updateBonusById(bonus); 
		if(Common.notEmptyStr(bonus.getName())){
			//更新主题名称
			PictorialTopic pt = pictorialTopicBiz.getPictorialTopicBonus(bonus.getIdentifier());
			pt.setName(bonus.getName());
			pt.setDescription(bonus.getIntro());
			pictorialTopicBiz.updatePictorialTopicById(pt);
		}
	}
	//修改红利申请
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout=10)
	public void updateBonusApplyById(BonusApply bonusApply, Bonus bonus, Order order)
			throws AppBusinessException {
		bonusDao.updateBonusApplyById(bonusApply);  
		updateBonusById(bonus);
		//如果审核通过则添加一条订单
		if("02".equals(bonusApply.getStatus())){
			//添加一个订单
			String id = identifierBiz.generateId("order");
			order.setIdentifier(id);
			order.setStatus("02");
			order.setType("06");
			OrderProduct op = new OrderProduct();
			op.setOrder(id);
			op.setProduct(bonus.getIdentifier());
			op.setQuantity("1");
			productBiz.insertOrderForRed(order, op);
		}
	}
	//删除红利
	@Override
	public void deleteBonusById(String bonusId) throws AppBusinessException {
		bonusDao.deleteBonusById(bonusId);
	}
	//在后台查询红利申请的会员
	@Override
	public PageModel getBonusApplyAll(String bonus, String status,
			Boolean enabled, Integer pageSize, Integer page) throws AppBusinessException {
		if(page==null || page<1)
			page = 1;
		if(pageSize==null || pageSize<1)
			pageSize = 10;
		int startId = (page - 1) * pageSize;
		Map<String,Object> map = new HashMap<String,Object>(); 
		map.put("bonus", Common.notEmptyStr(bonus)?bonus:null);
		map.put("status", Common.notEmptyStr(status)?status:null);
		map.put("enabled", enabled);
		map.put("startId", startId);
		map.put("pageSize", pageSize);
		List<BonusApply> list = bonusDao.getBonusApplyAll(map);
		int count = getBonusApplyCount(bonus, status, enabled);
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(list);
		pm.setPageSize(pageSize);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + pageSize - 1) / pageSize);
		return pm;
	}
	//在后台查询红利申请的会员总量
	@Override
	public Integer getBonusApplyCount(String bonus, String status,
			Boolean enabled) throws AppBusinessException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("bonus", Common.notEmptyStr(bonus)?bonus:null);
		map.put("status", Common.notEmptyStr(status)?status:null);
		map.put("enabled", enabled);
		return bonusDao.getBonusApplyCount(map);
	}
	
	
	
	
	
	@Override
	public PageModel getDoingByBonus(String bonus, int page)
			throws AppBusinessException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("enabled", true);
		map.put("bonus", bonus);
		int count = bonusDao.getDoingByBonusCount(map);
		
		int size = PageSize.BONUS_DOING;
		Integer startId = (page - 1) * size;
		map.put("startId", startId);
		map.put("pageSize", size);
		List<Doing> doingList = bonusDao.getDoingByBonus(map);
		
		
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(doingList);
		pm.setPageSize(size);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + size- 1) / size);
		 
		return pm;
	}
	@Override
	public void updateViewAmount(String bonus) throws AppBusinessException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("identifier", bonus);
		map.put("viewAmount", 1);
		bonusDao.updateViewAmount(map);
	}
	
	@Override
	public void updateApplyNums(String bonus) throws AppBusinessException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("identifier", bonus);
		map.put("applyNums", 1);
		bonusDao.updateApplyNums(map);
	}

	@Override
	public PageModel getBonusList(int page) throws AppBusinessException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("enabled", true);
		map.put("type", BonusType.PRODUCT.getValue());
		int count = bonusDao.getBonusListCount(map);
		
		int size = PageSize.BONUS_F_M;
		Integer startId = (page - 1) * size;
		map.put("startId", startId);
		map.put("pageSize", size);
		List<Bonus> bonusList = bonusDao.getBonusList(map);
		for (Bonus bonus : bonusList) {
			bonus.setApplyMember(getLastApplyMember(bonus.getIdentifier()));
		}
		
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(bonusList);
		pm.setPageSize(size);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + size- 1) / size);
		 
		return pm;
	}
	@Override
	public Bonus getBonusById(String id) throws AppBusinessException {
		if(Common.empty(id)) return null;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("identifier", id);
		List<Bonus> list = bonusDao.getBonusList(map);
		if(list != null && list.size() >0 ){
			Bonus bonus = list.get(0);
			bonus.setApplyMember(getLastApplyMember(bonus.getIdentifier()));
			return bonus;
		}
		return null;
	}
	@Override
	public List<Member> getLastApplyMember(String bonus)
			throws AppBusinessException {
		if(Common.empty(bonus)) return null;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("bonus", bonus);
		map.put("startId", 0);
		map.put("pageSize", 13);
		
		return bonusDao.getApplyMember(map);
	}
	@Override
	public List<Member> getSucApplyMember(String bonus)
			throws AppBusinessException {
		if(Common.empty(bonus)) return null;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("bonus", bonus);
		map.put("status", "02");
		
		return bonusDao.getApplyMember(map);
	}
	@Override
	public void insertBonusApply(BonusApply bonusApply)
			throws AppBusinessException {
		if(bonusApply == null) return ;
		bonusApply.setEnabled(true);
		bonusApply.setStatus("01");
		bonusDao.insertBonusApply(bonusApply);
	}
	@Override
	public boolean isExistBonusApply(String bonus, String family)
			throws AppBusinessException {
		if(Common.empty(bonus) || Common.empty(family)) return false;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("bonus", bonus);
		map.put("family", family);
		List<BonusApply> bonusApply = bonusDao.getBonusApply(map);
		if(bonusApply != null && bonusApply.size() > 0) return true;
		return false;
	}
	@Override
	public AlertMsg applyBonus(Doing doing,String pictureList, String bonus,String ip,Member member,String memo)
			throws AppBusinessException {
		AlertMsg aMsg = new AlertMsg(); 
		if(isExistBonusApply(bonus, member.getFamily())){
			aMsg.setCode(AlertMsgCode.FAILURE.getValue());
			aMsg.setMsg("亲~你已经申请过了哦， 去看看其它红利吧！");
		}else{
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();// 事务定义类
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 设置事务传播属性
			TransactionStatus status = transactionManager.getTransaction(def);// 返回事务对象
			try {
				/*
				Bonus bonusO = getBonusById(bonus);
				String content = doing.getContent();
				if(content.indexOf("#"+bonusO.getName()+"#") == -1){
					doing.setContent("#"+bonusO.getName()+"# "+content);
				}*/
				doingBiz.postDoingProduct(doing,null,ip,false,member); 
				BonusApply bonusApply = new BonusApply();
				bonusApply.setBonus(bonus);
				bonusApply.setDoing(doing.getIdentifier());
				bonusApply.setEnabled(true);
				bonusApply.setFamily(member.getFamily());
				bonusApply.setMember(member.getIdentifier());
				bonusApply.setStatus("01");
				bonusApply.setMemo(memo); 
				bonusDao.insertBonusApply(bonusApply);
				updateApplyNums(bonus);
				//更新用户地址，联系信息，用户名等
				MemberDetail memberDetail = member.getMemberDetail();
				memberDetail.setMember(member.getIdentifier());
				updateApplyInfo(member.getUsername(), memberDetail);
				transactionManager.commit(status);// 提交事务
				aMsg.setCode(AlertMsgCode.SUCCESS.getValue());
			} catch (Exception e) {
				e.printStackTrace();
				transactionManager.rollback(status);// 回滚事务
				aMsg.setCode(AlertMsgCode.FAILURE.getValue());
				aMsg.setMsg("亲~申请失败，请稍后再试！");
				return aMsg;
			//	throw new AppBusinessException(e);
			}
		}
		
		return aMsg;
	}
	public AlertMsg checkApplyBonus(String bonus,String family)throws AppBusinessException{
		AlertMsg aMsg = new AlertMsg();
		if(isExistBonusApply(bonus, family)){
			aMsg.setCode(AlertMsgCode.FAILURE.getValue());
			aMsg.setMsg("亲~你已经申请过了哦， 去看看其它红利吧！");
		}else{
			aMsg.setCode(AlertMsgCode.SUCCESS.getValue());
		}
		return aMsg;
	}
	@Override
	public void updateApplyInfo(String username,
			MemberDetail memberDetail) throws AppBusinessException {
		Member member = new Member();
		member.setIdentifier(memberDetail.getMember());
		member.setUsername(username);
		memberBiz.updateMember(member);
		memberDetailBiz.updateMemberDetail(memberDetail);
	}
	@Override
	public List<Bonus> getCanApply(String bonus,String family) throws AppBusinessException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("bonus", bonus);
		map.put("family", family);
		map.put("startId", 0);
		map.put("pageSize", 5);
		map.put("enabled", true);
		
		return bonusDao.getCanApply(map);
	}
	@Override
	public List<BonusApply> getApplyNow() throws AppBusinessException {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("startId", 0);
		map.put("pageSize", 15);
		return bonusDao.getApplyNow(map);
	}
	@Override
	public Bonus getIndexBonus() throws AppBusinessException {
		return bonusDao.getIndexBonus();
	}
	@Override
	public List<DoingPictorial> getIndexBonusReply() throws AppBusinessException {
		return bonusDao.getIndexBonusReply();
	}
	
	
	
}
